package cn.michael.dev.leetcode;

import cn.michael.dev.entity.ListNode;

/**
 * Created by hufenggang on 2021/8/10.
 *
 * 问题描述:
 * 给你两个非空的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储一位数字。
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 */
public class Problem2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode index1 = l1, index2 = l2;
        ListNode head = new ListNode(-1, l1);

        int sum = 0;
        while (index1 != null && index2 != null) {

            int value = (index1.val + index2.val + sum) % 10;
            index1.val = value;

            sum = (index1.val + index2.val + sum) > 9 ? 1 : 0;

            index1 = index1.next;
            index2 = index2.next;
            head = head.next;
        }

        ListNode node = index1 == null ? index2 : index1;
        // 跳出循环之后
        if (node != null) {
            head.next = node;

            while(node.next != null && sum == 1) {
                if(node.val + sum > 9) {
                    node.val = (node.val + sum) % 10;
                    sum = 1;
                } else {
                    node.val = node.val +sum;
                    sum = 0;
                }
                node = node.next;
            }

            node.val = node.val + sum;
            if(node.val > 9) {
                node.val = node.val % 10;
                node.next = new ListNode(1);
            }
        } else if (sum == 1) {
            head.next = new ListNode(1);
        }


        return l1;
    }
}